package com.ruoyi.location.domain.login;

import com.ruoyi.location.exception.LocationRuntimeException;
import com.ruoyi.location.repository.LoginRepository;
import com.ruoyi.location.repository.generator.entity.LocationPhoneLoginCode;
import com.ruoyi.location.repository.generator.entity.LocationUserInfo;
import com.ruoyi.location.repository.generator.entity.SysUserGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.Random;

@Service
public class LoginDomainService {

    @Autowired
    private LoginRepository loginRepository;

    public void genCodeAndSend(Long phoneNum) {
        // code
        Random random = new Random();
        int randomNumber = 1000 + random.nextInt(9000); // 生成1000到9999之间的随机数

        loginRepository.savePhoneLoginCode(phoneNum, randomNumber);

        // todo 发送短信
    }

    /**
     * 验证失败抛错， 成功返回用户信息
     * @param phoneNum
     * @param code
     * @return
     */
    public SysUserGen checkPhoneCode(Long phoneNum, int code) {
        LocationPhoneLoginCode loginCode = loginRepository.getPhoneLoginCodeByPhoneNum(phoneNum);

        if (5211 == code) {
            // 白名单code，不做校验，直接通过

        } else {
            // 1. 校验验证码是否在10分钟内
            Date now = new Date();
            long timeDiff = now.getTime() - loginCode.getCtime().getTime();
            if (timeDiff > 10 * 60 * 1000) { // 10分钟 = 10 * 60 * 1000毫秒
                throw new LocationRuntimeException("验证码已过期");
            }
            // 2. 校验验证码是否匹配
            boolean ifMatch = Objects.equals(String.valueOf(code), loginCode.getMsgCode());
            if (!ifMatch) {
                throw new LocationRuntimeException("验证码错误");
            }

        }

        // 3. 用户不存在，则注册用户
        SysUserGen sysUser = loginRepository.insertIfNullSysUser(phoneNum);
        LocationUserInfo userInfo = loginRepository.insertIfNullLocationUser(sysUser.getUserId(), phoneNum);
        return sysUser;
    }
}
